layui.use(['laydate', 'layer', 'form', 'configs', 'template', 'formSelects', 'echarts','excel'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer,
        form = layui.form,
        template = layui.template,
        config = layui.configs,
        formSelects = layui.formSelects,
        echarts = layui.echarts,
        excel = layui.excel;
    var flag = 0, colors = ['#ac3ff2', '#ff6c00', '#EAEA26', '#34da62', '#3cefff', '#FE5656'], laydateObj = {}, excelData = null;
    var myChart = echarts.init(document.getElementById("hourChart"), "dark");
    var initType = $('[name="trendType"]:checked').val();
    initAll();

    function initAll() {
        initLayDate(initType);
        getArea();
    }

    // 监听类型选择
    form.on('radio(trendType)', function (data) {
        var startIpt = '<input type="text" class="layui-input" id="startTime" name="startTime"  autocomplete="off">';
        var endIpt = '<input type="text" class="layui-input" id="endTime" name="endTime"  autocomplete="off">';
        $(".startTime").empty().html(startIpt);
        $(".endTime").empty().html(endIpt);
        initLayDate(data.value)
    });

    function initLayDate(charttype) {
        var sv = null;
        if (charttype === '1') { // 1-时 'yyyy-MM-dd HH:mm'
            //提前24小时
            sv = new Date(new Date().getTime() - 3600 * 1000 * 24);
            laydateObj = {
                startValue: formatDateStr(charttype, sv),
                endValue: formatDateStr(charttype),
                format: 'yyyy-MM-dd HH:mm',
                type: 'datetime',
                ready: function () { //删除分秒选择框，时选择居中
                    $(".layui-laydate .layui-laydate-footer").on("click", "span.laydate-btns-time", function () {
                        var hourLi = $(this).parents(".layui-laydate").find('.laydate-time-show .laydate-time-list > li:first-child');
                        hourLi.nextAll().remove();
                        hourLi.css("width", "100%");
                        hourLi.find("ol li").css({"padding-left": 115})
                    });
                }
            };
        } else if (charttype === '2') { // 2-日 'yyyy-MM-dd'
            //提前30天
            sv = new Date(new Date().getTime() - 3600 * 1000 * 24 * 30);
            laydateObj = {
                startValue: formatDateStr(charttype, sv),
                endValue: formatDateStr(charttype),
                format: 'yyyy-MM-dd',
                type: 'date',
                ready: function () {
                }
            };
        } else { // 3-月 'yyyy-MM'
            //提前一个月
            sv = new Date(new Date().getTime() - 3600 * 1000 * 24 * 30);
            laydateObj = {
                startValue: formatDateStr(charttype, sv),
                endValue: formatDateStr(charttype),
                format: 'yyyy-MM',
                type: 'month',
                ready: function () {
                }
            };
        }
        initDate(laydateObj);
    }

    function initDate(laydateObj) {
        laydate.render({
            elem: "#startTime",
            value: laydateObj.startValue,
            format: laydateObj.format,
            type: laydateObj.type,
            trigger: 'click',
            btns: ['clear', 'confirm'],
            ready: laydateObj.ready
        });
        laydate.render({
            elem: "#endTime",
            value: laydateObj.endValue,
            format: laydateObj.format,
            type: laydateObj.type,
            trigger: 'click',
            btns: ['clear', 'confirm'],
            ready: laydateObj.ready
        });
    }

    //获取区域
    function getArea() {
        $.ajax({
            url: config.motorBaseUrl + "/area_info/select/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    if (result.data != null && result.data.length > 0) {
                        $(".areaMenu").html(template("motor-areas-tpl", result));
                        if (flag === 0) {
                            form.val('paramChart', {
                                'areaId': result.data[0].areaId
                            });
                        }
                        form.render('select');
                        var areaId = $(".areaMenu option:checked").val();
                        getMotors(areaId);
                    }
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    // 查马达
    function getMotors(areaId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/selectMortor/v1.0",
            type: "post",
            datatype: "json",
            data: {
                areaId: areaId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    if (result.data != null && result.data.length > 0) {
                        $(".multi-motors").html(template("motors-tpl", result));
                        formSelects.render('select-motor');
                        formSelects.btns('select-motor', ['select', 'remove'], {show: '', space: '10px'});
                        formSelects.value('select-motor', 'val');
                        if (flag === 0) {
                            $(".icon-quanxuan").click();
                            $(".searchBtn").click()
                        }
                    }
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //监听区域选择
    form.on('select(areaMenu)', function (data) {
        flag = 1;
        form.render('select');
        $(".multi-motors").html("");
        formSelects.render('select-motor');
        getMotors(data.value)
    });

    //查询
    $(".searchBtn").click(function () {
        form.on('submit(search)', function (data) {
            getChartData(data.field);
            return false;
        });
    });

    //获取charts数据
    function getChartData(data) {
        var thisTrendType = data.trendType;
        var moNum = data.moIds.split(",").length;
        var connectNulls = false; // 折线图是否断点续连
        $.ajax({
            url: config.motorBaseUrl + "/chart/get/trend/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            beforeSend: function () {
                myChart.clear();
                myChart.showLoading();
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    var title = {
                        text: $(".areaMenu option:selected").text(),
                        subtext: $("#startTime").val() + '至' + $("#endTime").val(),
                        type: $("[name=trendType]:checked").attr("title")
                    };
                    var resData = result.data;
                    excelData = result.data;
                    if (Object.keys(resData).length > 0) {
                        if (moNum === 1) { // 仅选了单个马达
                            var mname = $('.multi-motors option:selected').text();
                            title.text +=  mname + '马达振幅' + title.type;
                            var xaxis = [], upperLimitInner = [], lowerLimitInner = [], yaxis = [];
                            for (var k in resData) {
                                if (thisTrendType === '1') {
                                    xaxis.push([k.replace(' ', '\n')]);
                                } else {
                                    xaxis.push([k.slice(0, 10)]);
                                }
                                var datalist = resData[k][0];
                                upperLimitInner.push(datalist.upperLimitInner === -1 ? '' : datalist.upperLimitInner);
                                lowerLimitInner.push(datalist.lowerLimitInner === -1 ? '' : datalist.lowerLimitInner);
                                yaxis.push(datalist.rockData === null ? '' : datalist.rockData);
                            }
                            renderSingleChart(title,mname, xaxis, upperLimitInner,lowerLimitInner,yaxis);
                        } else {
                            title.text += '马达振幅' + title.type;
                            var list = [], moNames = ['product'], moDatas = [], seriesArr = [];
                            for (var k in resData) {
                                list.push(resData[k]);
                                if (thisTrendType === '1') {
                                    moDatas.push([k.replace(' ', '\n')]);
                                } else {
                                    moDatas.push([k.slice(0, 10)]);
                                }
                            }
                            list[0].forEach((item, index) => {
                                moNames.push(item.moName);
                                seriesArr.push({
                                    type: 'line',
                                    connectNulls: connectNulls,
                                    smooth: true,
                                    smoothMonotone: 'x'
                                });
                            });
                            list.forEach((item, index) => {
                                item.forEach((ite, idx) => {
                                    moDatas[index].push(ite.rockData === null ? '' : ite.rockData)
                                });
                            });
                            moDatas.unshift(moNames);
                            // console.log(moDatas)
                            renderMultiChart(title, moDatas, seriesArr);
                        }
                    } else {
                        myChart.setOption({
                            backgroundColor: 'transparent', xAxis: {}, yAxis: {}
                        })
                    }
                } else {
                    layer.msg(result.stateMsg);
                }
            },
            complete: function () {
                myChart.hideLoading();
            }
        })
    }

    // 单个马达- 展示管制上下限
    function renderSingleChart(title, mname, xaxis, upperLimitInner,lowerLimitInner,yaxis){
        var singleOption = {
            title: {
                left: 'center',
                text: title.text,
                subtext: title.subtext
            },
            backgroundColor: 'transparent',
            color: colors,
            legend: {
                right: 10,
                orient: 'vertical'
            },
            tooltip: {
                trigger: 'axis'
            },
            grid: {
                left: '5%',
                right: '8%',
                bottom: '5%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: xaxis
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                name: mname,
                type: 'line',
                connectNulls: false,
                data: yaxis
            },{
                name: '管制上限',
                type: 'line',
                symbolSize: 0,
                connectNulls: false,
                data: upperLimitInner
            },{
                name: '管制下限',
                type: 'line',
                symbolSize: 0,
                connectNulls: false,
                data: lowerLimitInner
            }]
        };
        myChart.setOption(singleOption);
    }


    // 多个马达
    function renderMultiChart(title, moDatas, seriesArr) {
        var multiOption = {
            title: {
                left: 'center',
                text: title.text,
                subtext: title.subtext
            },
            backgroundColor: 'transparent',
            color: colors,
            legend: {
                right: 10,
                orient: 'vertical'
            },
            tooltip: {
                trigger: 'axis'
            },
            grid: {
                left: '5%',
                right: '8%',
                bottom: '5%',
                containLabel: true
            },
            dataset: {
                source: moDatas
            },
            xAxis: {
                name: '时间',
                type: 'category',
                boundaryGap: false
            },
            yAxis: {name: 'mm/s'},
            series: seriesArr
        };
        myChart.setOption(multiOption);
    }

    window.onresize = function () {
        myChart.resize();
    };

    //导出excel
    $('.exportBtn').click(function () {
        var arrlist = [].concat.apply([], Object.values(excelData));
        // 过滤无振幅值
        var list = arrlist.filter(function(val){
            return val.rockData != null
        });
        // // excel的表头
        var head = {
            areaName: "区域名称",
            moName: "马达位置",
            recTime: "测量时间",
            rockData: "振幅数据",
            upperLimit: "振幅上限",
            lowerLimit: "振幅下限",
            upperLimitInner: "振幅管制上限",
            lowerLimitInner: "振幅管制下限"
        };
        var datalist = [];
        // 循环全部数据，按表头取出所需的字段值
        list.forEach(function(item){
            var obj = {};
            for(var k in head){
                if(k == 'upperLimitInner'){
                    obj[k] = item[k] == -1 ? '' : item[k] ;
                }else if(k == 'lowerLimitInner'){
                    obj[k] = item[k] == -1 ? '' : item[k] ;
                }else{
                    obj[k] = item[k];
                }
            }
            datalist.push(obj);
        });
        datalist.unshift(head);
        var filename = '马达' + $("[name=trendType]:checked").attr("title")  + $('#startTime').val() + '-' + $('#endTime').val() + '.xlsx';
        excel.exportExcel({
            sheet1: datalist
        }, filename, 'xlsx');
    });

    // 分秒为00
    function formatDateStr(types, date) {
        var date = date || new Date();
        var Y = date.getFullYear();
        var M = date.getMonth() + 1;
        M = M < 10 ? '0' + M : M;
        var D = date.getDate();
        D = D < 10 ? '0' + D : D;
        var h = date.getHours();
        h = h < 10 ? '0' + h : h;
        var m = date.getMinutes();
        m = m < 10 ? '0' + m : m;
        if (types === '1') {
            return Y + '-' + M + '-' + D + ' ' + h + ':00';
        } else if (types === '2') {
            return Y + '-' + M + '-' + D;
        } else {
            return Y + '-' + M;
        }
    }
});